package com.rjgc.emallsimulation.controller;

import com.rjgc.emallsimulation.adapter.ResultAdapter;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.UUID;

@RestController
@Slf4j
public class UploadController {
    @PostMapping("/upload")
    public Map<String,Object> upload(@RequestParam("file") MultipartFile file){
        String filePath="/www/wwwroot/101.201.249.192/img/";//"存储地址"
        if (file.isEmpty()) {
            ResultAdapter.singleResult("savePath","uploadfail");
        }
        String originalFilename = file.getOriginalFilename();
        String suffix = originalFilename.substring(originalFilename.indexOf("."));
        String localFileName = UUID.randomUUID().toString().replace("-","")+suffix;
        File f=new File(filePath+localFileName);
        try {
            if (!f.exists()) {
                file.transferTo(f);
                log.info("上传成功");
            } else {
                log.info("文件已存在!");
            }
        }catch (Exception ex){
            log.error("文件存储失败!");
        }

        return ResultAdapter.singleResult("savePath","http://101.201.249.192/img/"+localFileName);
    }
}
